<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>证书模板编辑器</span>
        <el-button style="float: right; padding: 3px 0" link @click="goBack">返回</el-button>
      </div>
      
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form :model="templateInfo" label-width="100px" size="small">
            <el-form-item label="模板名称">
              <el-input v-model="templateInfo.name" disabled></el-input>
            </el-form-item>
            <el-form-item label="模板类型">
              <el-input v-model="templateInfo.type" disabled></el-input>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      
      <el-divider content-position="center">编辑内容</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="24">
          <div class="editor-toolbar">
            <el-button-group>
              <el-button size="small" icon="el-icon-document" @click="saveContent">保存</el-button>
              <el-button size="small" icon="el-icon-view" @click="previewContent">预览</el-button>
              <el-button size="small" icon="el-icon-refresh" @click="resetContent">重置</el-button>
            </el-button-group>
            
            <span class="editor-type">
              <el-radio-group v-model="editorType" size="small" @change="handleEditorTypeChange">
                <el-radio-button label="rich">富文本编辑</el-radio-button>
                <el-radio-button label="html">HTML编辑</el-radio-button>
              </el-radio-group>
            </span>
          </div>
          
          <!-- 富文本编辑器 -->
          <div v-show="editorType === 'rich'" class="rich-editor-container">
            <editor
              ref="richEditor"
              v-model="editorContent"
              :init="richEditorInit"
              :disabled="loading"
            ></editor>
          </div>
          
          <!-- HTML代码编辑器 -->
          <div v-show="editorType === 'html'" class="html-editor-container">
            <textarea
              ref="htmlEditor"
              v-model="editorContent"
              :disabled="loading"
              class="html-editor"
            ></textarea>
          </div>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="24">
          <el-divider content-position="center">变量列表</el-divider>
          <el-table :data="variableList" size="small" border style="width: 100%">
            <el-table-column prop="name" label="变量名" width="180"></el-table-column>
            <el-table-column prop="description" label="描述"></el-table-column>
            <el-table-column prop="defaultValue" label="默认值" width="180"></el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  link
                  @click="insertVariable(scope.row.name)"
                >插入</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 预览对话框 -->
    <el-dialog title="模板预览" :visible.sync="previewVisible" width="60%" append-to-body>
      <div class="preview-container" v-loading="previewLoading">
        <div v-html="previewContent"></div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Editor from '@tinymce/tinymce-vue'
import { getTemplate, updateTemplate, previewTemplate } from "@/api/qep/certificate/template";
import { listTemplateVariables } from "@/api/qep/certificate/template";

export default {
  name: "WordEditor",
  components: {
    Editor
  },
  data() {
    return {
      // 模板ID
      templateId: null,
      // 模板信息
      templateInfo: {
        id: null,
        name: '',
        type: '',
        templateFormat: 'HTML',
        editorType: 'rich'
      },
      // 编辑器内容
      editorContent: '',
      // 编辑器类型 (rich: 富文本, html: HTML)
      editorType: 'rich',
      // 原始内容
      originalContent: '',
      // 加载状态
      loading: false,
      // 预览相关
      previewVisible: false,
      previewContent: '',
      previewLoading: false,
      // 变量列表
      variableList: [],
      // 富文本编辑器配置
      richEditorInit: {
        height: 500,
        menubar: 'file edit view insert format tools table help',
        plugins: [
          'advlist autolink lists link image charmap print preview anchor',
          'searchreplace visualblocks code fullscreen',
          'insertdatetime media table paste code help wordcount'
        ],
        toolbar:
          'undo redo | formatselect | bold italic backcolor | \
          alignleft aligncenter alignright alignjustify | \
          bullist numlist outdent indent | removeformat | help | image zycapture | wordpaster importwordtoimg pptimport pdfimport netpaster |\
          zyoffice zywordexport zyoofficepdf', 
          //高度
          height: 200,
          paste_data_images: true,
          width :  '100%',
        branding: false
      }
    };
  },
  created() {
    // 从路由获取模板ID
    this.templateId = this.$route.query.id;
    if (this.templateId) {
      this.getTemplateInfo();
      this.getVariableList();
    } else {
      this.$modal.msgError("未指定模板ID");
      this.goBack();
    }
  },
  methods: {
    // 获取模板信息
    getTemplateInfo() {
      this.loading = true;
      getTemplate(this.templateId).then(response => {
        this.templateInfo = response.data;
        this.editorContent = this.templateInfo.editorContent || '';
        this.originalContent = this.editorContent;
        this.editorType = this.templateInfo.editorType || 'rich';
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.$modal.msgError("获取模板信息失败");
      });
    },
    
    // 获取变量列表
    getVariableList() {
      listTemplateVariables(this.templateId).then(response => {
        this.variableList = response.data || [];
      }).catch(() => {
        this.$modal.msgError("获取变量列表失败");
      });
    },
    
    // 保存内容
    saveContent() {
      this.loading = true;
      const data = {
        id: this.templateId,
        editorContent: this.editorContent,
        editorType: this.editorType
      };
      
      updateTemplate(data).then(response => {
        this.loading = false;
        this.$modal.msgSuccess("保存成功");
        this.originalContent = this.editorContent;
      }).catch(() => {
        this.loading = false;
        this.$modal.msgError("保存失败");
      });
    },
    
    // 预览内容
    previewContent() {
      this.previewVisible = true;
      this.previewLoading = true;
      
      // 如果内容未修改，直接调用API预览
      if (this.editorContent === this.originalContent && this.templateInfo.id) {
        previewTemplate(this.templateInfo.id).then(response => {
          // 判断返回类型
          if (response instanceof Blob) {
            // 如果是二进制文件，尝试读取为文本
            const reader = new FileReader();
            reader.onload = () => {
              this.previewContent = reader.result;
              this.previewLoading = false;
            };
            reader.readAsText(response);
          } else {
            // 否则直接显示内容
            this.previewContent = response;
            this.previewLoading = false;
          }
        }).catch(() => {
          this.previewLoading = false;
          this.$modal.msgError("预览失败");
        });
      } else {
        // 如果内容已修改，简单预览当前内容
        this.previewContent = this.editorContent;
        this.previewLoading = false;
      }
    },
    
    // 重置内容
    resetContent() {
      this.$modal.confirm('确定要重置为原始内容吗？未保存的修改将丢失。').then(() => {
        this.editorContent = this.originalContent;
      });
    },
    
    // 切换编辑器类型
    handleEditorTypeChange(type) {
      this.editorType = type;
    },
    
    // 插入变量
    insertVariable(varName) {
      const variable = '${' + varName + '}';
      
      if (this.editorType === 'rich' && this.$refs.richEditor) {
        const editor = this.$refs.richEditor.editor;
        editor.execCommand('mceInsertContent', false, variable);
      } else if (this.editorType === 'html') {
        // 获取当前光标位置
        const textarea = this.$refs.htmlEditor;
        const startPos = textarea.selectionStart;
        const endPos = textarea.selectionEnd;
        
        // 在光标位置插入变量
        this.editorContent = 
          this.editorContent.substring(0, startPos) + 
          variable + 
          this.editorContent.substring(endPos, this.editorContent.length);
          
        // 重新设置光标位置
        this.$nextTick(() => {
          textarea.focus();
          textarea.selectionStart = startPos + variable.length;
          textarea.selectionEnd = startPos + variable.length;
        });
      }
    },
    
    // 返回
    goBack() {
      if (this.editorContent !== this.originalContent) {
        this.$modal.confirm('您有未保存的更改，确定要离开吗？').then(() => {
          this.$router.push({ path: '/certificate/template' });
        });
      } else {
        this.$router.push({ path: '/certificate/template' });
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  margin-top: 0;
}
.editor-toolbar {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.rich-editor-container {
  border: 1px solid #dcdfe6;
  margin-bottom: 20px;
}

.html-editor-container {
  margin-bottom: 20px;
}

.html-editor {
  width: 100%;
  height: 500px;
  border: 1px solid #dcdfe6;
  padding: 10px;
  font-family: monospace;
  font-size: 14px;
  line-height: 1.6;
  resize: vertical;
}

.preview-container {
  min-height: 300px;
  border: 1px solid #dcdfe6;
  padding: 20px;
  background-color: #fff;
}
</style> 